package com.dq.service;

import com.dq.cache.constant.CacheConstant;
import com.dq.cache.MyRedisComponent;
import com.dq.domain.sys.user.user.base.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @创建人 gewenzhen
 * @创建时间 2019/9/9
 * @描述
 */
@Service
public class TokenService {
    @Autowired
    MyRedisComponent myRedisComponent;

    public String createToken(SysUser user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String tokenKey = CacheConstant.USER_TOKEN_CACHE_PREFIX + token;
        myRedisComponent.set(tokenKey, user, CacheConstant.USER_TOKEN_CACHE_EXPIRE);
        return token;
    }

    public boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        String tokenKey = CacheConstant.USER_TOKEN_CACHE_PREFIX + token;
        if (myRedisComponent.hasKey(tokenKey)) {
            // 有操作 更新token过期时间
            myRedisComponent.expire(tokenKey, CacheConstant.USER_TOKEN_CACHE_EXPIRE);
            return true;
        }
        return false;
    }

    public void deleteToken(String token) {
        String tokenKey = CacheConstant.USER_TOKEN_CACHE_PREFIX + token;
        myRedisComponent.del(tokenKey);
    }

    public SysUser getUserByToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String tokenKey = CacheConstant.USER_TOKEN_CACHE_PREFIX + token;
        SysUser sysUser = (SysUser) myRedisComponent.get(tokenKey);
        if (sysUser == null) {
            return null;
        }
        // 有操作 更新token过期时间
        myRedisComponent.expire(tokenKey, CacheConstant.USER_TOKEN_CACHE_EXPIRE);
        return sysUser;
    }
}
